from ..data.packages import loadPackages, PackageVars, requestPackage

import sys
import time
from rich import print as rprint
from rich.table import Table
from rich.console import Console

class SparkStoreAppCli:
    '''SparkStoreAppCli

    - pkgs 列出所有软件包
    - apps 列出所有应用
    '''
    elapsed = time.monotonic()

    table = Table()
    console = Console()

    def pkgs(self):
        for pkg in loadPackages():
            if pkg.Package:
                print(pkg.Package)
        print('-- elapsed: %.2f s --' % (time.monotonic() - self.elapsed), file=sys.stderr)

    def apps(self):
        elapsed = time.monotonic()
        for pkg in loadPackages():
            if pkg.Package:
                rprint(pkg.Package)
        print('-- elapsed: %.2f s --' % (time.monotonic() - self.elapsed), file=sys.stderr)

    def packages(self):
        
        self.table.add_column(PackageVars.Package)
        self.table.add_column(PackageVars.Version)
        self.table.add_column(PackageVars.Size)
        
        for pkg in loadPackages():
            self.table.add_row(pkg.Package, pkg.Version, pkg.Size)

        self.console.print(self.table)
        print('-- elapsed: %.2f s --' % (time.monotonic() - self.elapsed), file=sys.stderr)

    def search(self, name=''):
        self.table.add_column(PackageVars.Package)
        self.table.add_column(PackageVars.Version)
        self.table.add_column(PackageVars.Size)

        for pkg in loadPackages():
            if name in pkg.Package:
                self.table.add_row(pkg.Package, pkg.Version, pkg.Size)
        
        self.console.print(self.table)
        print('-- elapsed: %.2f s --' % (time.monotonic() - self.elapsed), file=sys.stderr)

    def install(self, name=None):
        if name == None:
            print('please input package name')
            return
        
        # requestPackage()